package com.zwd.deep.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zwd.deep.common.ResultEnum;
import com.zwd.deep.handle.exception.GlobalException;
import com.zwd.deep.utils.HttpServletUtil;
import com.zwd.deep.utils.JwtUtil;
import io.jsonwebtoken.JwtException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Enumeration;
import java.util.Objects;

/**
 * Token拦截器
 *
 * @author wanjunhong
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    /**
     * 请求拦截验证token
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理
     * @return 处理结果
     * @throws JwtException JWT异常
     */
    @Override
    public boolean preHandle(@Nullable HttpServletRequest request, @Nullable HttpServletResponse response, @Nullable Object handler) throws JwtException {
        //地址过滤
        String uri = Objects.requireNonNull(request).getRequestURI();
        log.info("请求地址：{}", uri);
        if (uri.startsWith("/users/login")) {
            return true;
        }
        //token验证
        String token = HttpServletUtil.getToken();
        if (StrUtil.isBlank(token)) {
            throw new GlobalException(ResultEnum.NO_LOGIN);
        }
        if (JwtUtil.isTokenExpired(token)) {
            throw new GlobalException(ResultEnum.LOGIN_EXPIRED);
        }
        return true;
    }
}
